﻿/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.Tools;
using System.Windows.Media.Animation;
using myBoard.App.Business;
using myBoard.Framework;

namespace myBoard.App.Controls
{
    /// <summary>
    /// Interaction logic for LocalMagnetsExplorer.xaml
    /// </summary>

    public partial class LocalMagnetsExplorer : System.Windows.Controls.UserControl
    {

        // Fields
        private MorphingItem _currentlyDraggedItem;
        private bool _isExplorerVisible;
        private Storyboard _showMagnetsSB; 
        private Storyboard _hideMagnetsSB;
        private Storyboard _movePreviousSB;
        private Storyboard _moveNextSB;
        public delegate void DeleteMagnetRequestedHandler(MagnetEx magnetEx);
        public event DeleteMagnetRequestedHandler DeleteMagnetRequested;

        // Properties
        public MorphingItem CurrentlyDraggedItem
        {
            get
            {
                return _currentlyDraggedItem;
            }
            set
            {
                _currentlyDraggedItem = value;
            }
        }


        // Constructor
        public LocalMagnetsExplorer()
        {
            this.InitializeComponent();
            _showMagnetsSB = this.Resources["ShowMagnets"] as Storyboard;
            _hideMagnetsSB = this.Resources["HideMagnets"] as Storyboard;
            _moveNextSB = this.Resources["MoveNext"] as Storyboard;
            _movePreviousSB = this.Resources["MovePrevious"] as Storyboard;
            this._hideShowLibBut.Click += new RoutedEventHandler(this.HideShowLibBut_Click);
            _magnetsList.Loaded += new RoutedEventHandler(_magnetsList_Loaded);
            _nextBt.Click += new RoutedEventHandler(_nextBt_Click);
            _previousBt.Click += new RoutedEventHandler(_previousBt_Click);
        }

        void _previousBt_Click(object sender, RoutedEventArgs e)
        {
            if (_magnetsList.Margin.Left < 0)
            {
                foreach (Timeline timeline in _movePreviousSB.Children)
                {
                    if (timeline.Name == "MovePreviousMarginTimeline")
                    {
                        ((ThicknessAnimationUsingKeyFrames)timeline).KeyFrames[0].Value = new Thickness(_magnetsList.Margin.Left + _magnetsListBorder.Width, 0, 0, 0);
                    }
                }

                this.BeginStoryboard(_movePreviousSB);
            }
        }

        void _nextBt_Click(object sender, RoutedEventArgs e)
        {
            if (!IsItemVisible(_magnetsList,_magnetsList.Items.Count-1))
            {
                foreach (Timeline timeline in _moveNextSB.Children)
                {
                    if (timeline.Name == "MoveNextMarginTimeline")
                    {
                        ((ThicknessAnimationUsingKeyFrames)timeline).KeyFrames[0].Value = new Thickness(_magnetsList.Margin.Left - _magnetsListBorder.Width, 0, 0, 0);
                    }
                }
                this.BeginStoryboard(_moveNextSB);
            }
        }

        void _magnetsList_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateHideMagnetsSB();
            RetractLibrary();
            AdjustMagnetsListBorderWidth();
        }

        private void UpdateHideMagnetsSB()
        {
            foreach (Timeline timeline in _hideMagnetsSB.Children)
            {
                if (timeline.Name == "ThicknessAnimation")
                {
                    ((ThicknessAnimationUsingKeyFrames)timeline).KeyFrames[0].Value = new Thickness(-(_magnetsList.ActualWidth + 20), 0, 0, 0);
                    break;
                }
            }
        }
        
        public void ExtendLibrary()
        {
            this.BeginStoryboard(_showMagnetsSB);
            _isExplorerVisible=true;
        }

        public void RetractLibrary()
        {
            this.BeginStoryboard(_hideMagnetsSB);
            _isExplorerVisible = false;
        } 

        private void HideShowLibBut_Click(object sender, RoutedEventArgs e)
        {
            Storyboard storyboard;
            if (_isExplorerVisible)
            {
                storyboard = base.FindResource("RotateToNormalForm") as Storyboard;
                if (storyboard != null)
                {
                    base.BeginStoryboard(storyboard);
                }
            }
            else
            {
                storyboard = base.FindResource("RotateToCrossForm") as Storyboard;
                if (storyboard != null)
                {
                    base.BeginStoryboard(storyboard);
                }
            }
        }               

        private void _magnetIcon_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            FrameworkElement fe = sender as FrameworkElement;
            MagnetEx magnetEx = fe.DataContext as MagnetEx;

            MorphingItem morphingItem = new MorphingItem();
            morphingItem._iconImage.Source = magnetEx.Magnet.Icon;
            morphingItem._thumbnailImage.Source = magnetEx.Magnet.Thumbnail;
            //morphingItem._thumbnailImage.Source = Framework.Tools.GetBitmapImageFromFrameworkElement((FrameworkElement)magnetEx.Magnet);
            Point mouseCoordOnRoot = Mouse.GetPosition(_root);
            Point mouseCoordOnIcon = Mouse.GetPosition(fe);
            Canvas.SetTop(morphingItem, mouseCoordOnRoot.Y-(mouseCoordOnIcon.Y));
            Canvas.SetLeft(morphingItem, mouseCoordOnRoot.X-(mouseCoordOnIcon.X));
            morphingItem.FirstClickPoint = mouseCoordOnIcon;
            morphingItem.Magnet = magnetEx;
            _currentlyDraggedItem = morphingItem;
            _root.Children.Add(morphingItem);
            
        }

        public void RemoveMorphingItem(MorphingItem item)
        {
            _root.Children.Remove(item);
            _currentlyDraggedItem = null;
        }

        /// <summary>
        /// We use this method to ajust the magnets listbox with
        /// </summary>
        /// <param name="lb"></param>
        /// <param name="Index"></param>
        /// <returns></returns>
        private bool IsItemVisible(ListBox lb, int Index)
        {

            if (lb.Items.Count == 0)
                return true;

            ListBoxItem lbi = lb.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;

            VirtualizingStackPanel vsp = VisualTreeHelper.GetParent(lbi) as VirtualizingStackPanel;

            int FirstVisibleItem = (int)vsp.HorizontalOffset;

            int VisibleItemCount = (int)vsp.ViewportWidth;

            if (Index >= FirstVisibleItem && Index <= FirstVisibleItem + VisibleItemCount)
            {
                return true;
            }
            else
            {
                return false;
            }                
        }

        private void AdjustMagnetsListBorderWidth()
        {
            for (int Index = 0; Index < _magnetsList.Items.Count; Index++)
            {
                if (_magnetsList.Items.Count == 0)
                    return;

                ListBoxItem lbi = _magnetsList.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;

                VirtualizingStackPanel vsp = VisualTreeHelper.GetParent(lbi) as VirtualizingStackPanel;

                int FirstVisibleItem = (int)vsp.HorizontalOffset;

                int VisibleItemCount = (int)vsp.ViewportWidth;

                if (Index >= FirstVisibleItem && Index <= FirstVisibleItem + VisibleItemCount)
                {
                }
                else
                {
                    _magnetsListBorder.Width = (Index - 1) * lbi.ActualWidth;
                    return;
                }
            }
        }

        private void _removeMgtBt_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (DeleteMagnetRequested != null)
            {
                Button removeBt = sender as Button;
                DeleteMagnetRequested(removeBt.DataContext as MagnetEx);
            }            
        }
    }
}